<script setup lang="ts">
import server from "../axios.ts";
import {ref, onMounted, onUnmounted, reactive} from "vue";
import {
  ElForm,
  ElLoading,
  ElMessage,
  ElMessageBox,
  ElTable,
  type TableInstance,
} from "element-plus";
import FormDrawer from "./FormDrawer.vue";

const isLoading = ref(false);

interface HostInfo {
  /**
   * 主机信息
   */
  id: number;
  host_ip: string;
  username: string;
  password: string;
}

const tableData = ref<HostInfo[]>([]);
// 存储选中的行数据
const selectedRows = ref<HostInfo[]>([]);
const hostInfoTableRef = ref<TableInstance>();
const tableHeight = ref(0);

const getData = () => {
  server.get<HostInfo[]>('/hosts/get').then((res) => {
    tableData.value = res.data;
  }).catch((err) => {
    console.log(err);
  });
};

// 计算表格高度的函数
const calculateTableHeight = () => {
  const headerHeight = 118;
  const buttonAreaHeight = 40;
  tableHeight.value = window.innerHeight - headerHeight - buttonAreaHeight;
};

// 监听窗口大小变化
const handleResize = () => {
  calculateTableHeight();
};

// 处理表格选择变化事件
const handleSelectionChange = (val: HostInfo[]) => {
  selectedRows.value = val;
};

// 开始升级任务，接收选中的行数据

// 定义加载状态
const isUpgrading = ref(false);
// 定义进度条相关状态
const upgradeProgress = ref(0);
const progressInterval = ref<number | null>(null);

//选择固件开始升级
const uploadedFirmwareList = reactive({
  biosFirmwareID: '',
  cpldFirmwareID: '',
  bmcFirmwareID: '',
  fpgaFirmwareID: '',
  isForceRestart: '',
});
// 是否强制重启选择器
const forceRestartOptions = [
  {value: 'true', label: '是'},
  {value: 'false', label: '否'},
];
const selectFirmwareForm = ref<InstanceType<typeof ElForm>>();
// 新增：按类型分类的固件列表
const selectFirmwareDialogVisible = ref(false);

// 假设固件项的类型
interface FirmwareItem {
  id: number
  file_name: string
  // 其他属性
}

// 定义按类型分类的固件列表,用于固件升级下拉选择框
const biosFirmwareList = ref<FirmwareItem[]>([])
const bmcFirmwareList = ref<FirmwareItem[]>([])
const cpldFirmwareList = ref<FirmwareItem[]>([])
const fpgaFirmwareList = ref<FirmwareItem[]>([])
// 开始升级功能
const startUpgrade = () => {
  // 阻止页面刷新的处理函数
  const preventUnload = (e: BeforeUnloadEvent) => {
    // 阻止默认行为，现代浏览器会自动显示离开确认提示
    e.preventDefault();
  };

  // 添加 beforeunload 事件监听
  window.addEventListener('beforeunload', preventUnload);
  // 显示加载状态
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '升级中，请勿刷新页面，耐心等待...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  isUpgrading.value = true;

  // 模拟进度条更新
  progressInterval.value = window.setInterval(() => {
    if (upgradeProgress.value < 90) {
      upgradeProgress.value += 5;
    }
  }, 1000);
  selectFirmwareDialogVisible.value = false;
  // 检查并处理 undefined
  type FirmwareListKey = keyof typeof uploadedFirmwareList;
  for (const key in uploadedFirmwareList) {
    if (uploadedFirmwareList[key as FirmwareListKey] === undefined) {
      uploadedFirmwareList[key as FirmwareListKey] = '';
    }
  }
  console.log(uploadedFirmwareList);
  // 调用升级接口
  server.post('/upgrade', {
    "host_lists": selectedRows.value,
    "firmware_lists": uploadedFirmwareList,
    "is_force_restart": uploadedFirmwareList.isForceRestart,
  }).then((res) => {
    console.log('升级请求响应', res);
    if (res.status === 200) {
      getData();
      if (uploadedFirmwareList.isForceRestart === "false") {
        ElMessageBox.alert('升级完成，请手动重启紫金卡！', '提示', {
          confirmButtonText: '确定',
        });
      }
      resetSelectFirmwareForm();
    }
    // 完成进度条
    upgradeProgress.value = 100;
    ElMessage.success('升级完成,详细信息请查看日志');
    clearSelection();
    selectedRows.value = [];
  }).catch((err) => {
    console.log('升级请求出错', err);
    ElMessage.error('升级失败，请重试');
  }).finally(() => {
    // 移除 beforeunload 事件监听（升级完成后恢复允许刷新）
    window.removeEventListener('beforeunload', preventUnload);
    // 清除进度条定时器
    if (progressInterval.value) {
      window.clearInterval(progressInterval.value);
      progressInterval.value = null;
    }
    // 重置进度条
    upgradeProgress.value = 0;
    // 关闭加载状态
    loadingInstance.close();
    isUpgrading.value = false;
  });
}
// 获取固件列表
const startUpgradeSelectFirmware = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要升级的主机');
    return;
  }
  selectFirmwareDialogVisible.value = true;

  try {
    await getFirmwareList();
    // 清空旧数据
    biosFirmwareList.value = [];
    bmcFirmwareList.value = [];
    cpldFirmwareList.value = [];
    fpgaFirmwareList.value = [];
    firmwareList.value.forEach((item: any) => {
      switch (item.type) {
        case 'BIOS':
          biosFirmwareList.value.push(item);
          break;
        case 'BMC':
          bmcFirmwareList.value.push(item);
          break;
        case 'CPLD':
          cpldFirmwareList.value.push(item);
          break;
        case 'FPGA':
          fpgaFirmwareList.value.push(item);
      }
    });
  } catch (error) {
    console.error('获取固件列表出错:', error);
    ElMessage.error('获取固件列表失败，请稍后重试');
  }
}

// 定义重置表单方法
const resetSelectFirmwareForm = () => {
  selectFirmwareForm.value?.resetFields();
  // 手动重置 v-model 绑定的值
  uploadedFirmwareList.biosFirmwareID = '';
  uploadedFirmwareList.bmcFirmwareID = '';
  uploadedFirmwareList.cpldFirmwareID = '';
  uploadedFirmwareList.fpgaFirmwareID = '';
  uploadedFirmwareList.isForceRestart = '';
};
// 开始升级任务,开始升级弹出框 开始升级按钮监听事件
const startUpgradeTaskConfirm = () => {

  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要升级的主机');
    return;
  }
  // 检查是否至少选择了一个固件
  if (!uploadedFirmwareList.biosFirmwareID &&
      !uploadedFirmwareList.bmcFirmwareID &&
      !uploadedFirmwareList.cpldFirmwareID &&
      !uploadedFirmwareList.fpgaFirmwareID) {
    ElMessage.warning('请先选择要升级的固件');
    return;
  }
  if (!uploadedFirmwareList.isForceRestart) {
    ElMessage.warning('请选择是否强制重启');
    return;
  }
  if (uploadedFirmwareList.isForceRestart === 'true') {
    ElMessageBox.confirm('您已选择强制关机升级，可能会造成业务中断，请确认无风险再操作！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      startUpgrade()
    })
  } else {
    startUpgrade()
  }
};

// 清除多选状态的方法
const clearSelection = () => {
  if (hostInfoTableRef.value) {
    hostInfoTableRef.value.clearSelection();
    selectedRows.value = [];
  }
};
onMounted(() => {
  getData();
  calculateTableHeight();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});
// 添加主机抽屉标签
const formTitle = ref('添加主机');
// 确认按钮文本
const confirmText = ref('确认提交');
// 添加主机抽屉form表单
const addHostDrawerRef = ref<InstanceType<typeof FormDrawer>>();
// 显示表单抽屉
const showFormDrawerDiag = () => {
  formTitle.value = '添加主机';
  confirmText.value = '确认提交';
  if (addHostDrawerRef.value) {
    addHostDrawerRef.value.open()
  }
  form.value = {
    id: 0,
    host_ip: '',
    username: '',
    password: '',
  }
  isUpdating.value = false;
}

// 添加主机表单数据类型
interface FormData {
  id: number,
  host_ip: string,
  username: string,
  password: string,
}

// 添加主机表单数据
const form = ref<FormData>({
  id: 0,
  host_ip: '',
  username: '',
  password: '',
});
// 是否为更新状态
const isUpdating = ref(false);
// 表单实例
const formRef = ref<InstanceType<typeof ElForm>>()
// 编辑主机信息
const handleEdit = (row: HostInfo) => {
  formTitle.value = '编辑主机';
  confirmText.value = '确认修改';
  form.value.id = row.id;
  form.value.host_ip = row.host_ip;
  form.value.username = row.username;
  form.value.password = row.password;
  if (addHostDrawerRef.value) {
    addHostDrawerRef.value.open()
  }
  isUpdating.value = true;
}

//添加主机信息
const handleAddHost = () => {
  if (form.value.id !== 0) {
    server.post('/hosts/update', form.value).then((res) => {
      if (res.status === 200) {
        ElMessage.success(res.data);
        getData();
        addHostDrawerRef.value?.close();
        if (formRef.value) {
          formRef.value.resetFields();
        }
      } else {
        ElMessage.error(res.data);
        addHostDrawerRef.value?.hiddeLoading();
      }
    }).catch((err) => {
      console.log(err);
      ElMessage.error(err.data)
    })
  } else {
    if (addHostDrawerRef.value) {
      addHostDrawerRef.value.showLoading()
    }
    if (form.value.host_ip === '' || form.value.username === '' || form.value.password === '') {
      ElMessage.error('请填写完整的主机信息')
      if (addHostDrawerRef.value) {
        addHostDrawerRef.value.hiddeLoading()
      }
      return
    }
    server.post('/hosts/add', form.value).then((res) => {
      if (res.status === 201) {
        ElMessage.success(res.data);
        getData();
        if (addHostDrawerRef.value) {
          addHostDrawerRef.value.hiddeLoading()
          addHostDrawerRef.value.close()
        }
      }
    }).catch((err) => {
      if (err.status === 400) {
        ElMessage.error("该主机已存在,请重新添加!")
        if (addHostDrawerRef.value) {
          addHostDrawerRef.value.hiddeLoading()
        }
      }
    })
  }
}
// 关闭抽屉时重置表单
const onDrawerClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
//删除主机信息
const handleDelete = (row: HostInfo) => {
  ElMessageBox.confirm('确定删除该主机吗?', '警告')
      .then(() => {
        server.delete(`/hosts/delete/${row.id}`).then((res) => {
          if (res.status === 200) {
            ElMessage.success(res.data)
            getData()
          }
        })
      })
}
//固件对话框
const dialogTableVisible = ref(false);
const firmwareList = ref([])
const getFirmwareList = () => {
  return new Promise((resolve, reject) => {
    server.get(`/firmware/list`).then((res) => {
      if (res.status === 200) {
        firmwareList.value = res.data;
        resolve(res.data);
      } else {
        reject(new Error('获取固件列表失败'));
      }
    }).catch((err) => {
      reject(err);
    });
  });
};
//打开固件对话框
const openFirmwareDiag = () => {
  dialogTableVisible.value = true
  getFirmwareList()
}
//上传固件对话框
const fileList = ref([]);
const fileType = ref(''); // 用于存储选择的文件类型

// 上传前检查文件类型
const beforeUpload = (file: File) => {
  const isHpm = file.name.endsWith(".hpm");
  const isRpd = file.name.endsWith(".rpd");
  if (fileType.value == 'FPGA' && !isRpd) {
    ElMessage.error("FPGA版本只能上传rpd格式的文件!");
    return false;
  }
  if (fileType.value !== "FPGA" && !isHpm) {
    ElMessage.error("非FPGA版本只能上传hpm格式的文件!");
    return false;
  }
  if (!fileType.value) {
    ElMessage.error("请选择文件类型");
    return false;
  }
  if (isHpm) {
    return isHpm;
  }
  if (isRpd) {
    return isRpd;
  }
};

// 自定义固件上传方法
const customUpload = async (params: any) => {
  const file = params.file;
  const formData = new FormData();
  formData.append("firmware", file);
  formData.append("type", fileType.value);
  // 获取上传固件的 URL
  const uploadFirmwareURL = import.meta.env.VITE_UPLOAD_FIRMWARE_URL;

  // 显示加载提示
  const loadingInstance = ElLoading.service({
    lock: true,
    text: `正在上传 ${file.name}，请稍候...`,
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    const response = await server.post(uploadFirmwareURL, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    params.onSuccess(response.data, params.file);
  } catch (error) {
    params.onError(error, params.file);
    // 上传失败提示
    ElMessage.error(`${file.name} 上传失败，请重试`);
  } finally {
    // 关闭加载提示
    loadingInstance.close();
  }
};

// 上传成功处理
const handleUploadSuccess = (response: any, file: File) => {
  ElMessage.success(`${file.name} 上传成功`);
  console.log("上传成功:", response);
  getFirmwareList();
  fileList.value = []; // 清空文件列表
};

// 上传失败处理
const handleUploadError = (error: any) => {
  ElMessage.error(error.response.data.error);
  console.error("上传失败:", error.response.data.error);
};

// 删除固件方法
const handleDeleteFirmware = (row: any) => {
  ElMessageBox.confirm(`确定删除 ${row.file_name} 吗?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    server.delete(`/firmware/delete/${row.id}`).then((res) => {
      if (res.status === 200) {
        ElMessage.success(res.data);
        getFirmwareList();
      }
    }).catch((err) => {
      ElMessage.error(err.data);
    });
  })
}
//批量添加主机
const showBatchAddHost = ref(false)
const handleBatchAddHost = () => {
  showBatchAddHost.value = true
  batchHostsFormData.start_ip = '';
  batchHostsFormData.end_ip = '';
  batchHostsFormData.username = '';
  batchHostsFormData.password = '';
}

// 批量添加主机表单数据
interface batchHostsForm {
  start_ip: string,
  end_ip: string,
  username: string,
  password: string,
}

// 批量添加主机表单数据
const batchHostsFormData = reactive<batchHostsForm>({
  start_ip: '',
  end_ip: '',
  username: '',
  password: '',
})
const batchHostsFormRef = ref<InstanceType<typeof ElForm>>()
// 批量添加主机表单验证规则
const batchHostsFormRules = reactive({
  start_ip: [
    {required: true, message: '请输入起始IP地址', trigger: 'blur'},
  ],
  end_ip: [
    {required: true, message: '请输入结束IP地址', trigger: 'blur'},
  ],
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ]
});

// 批量添加主机表单提交
const handleBatchAddHostSubmit = () => {
  if (batchHostsFormRef.value) {
    // 调用 validate 方法进行表单验证
    batchHostsFormRef.value.validate((valid) => {
      if (valid) {
        isLoading.value = true
        server.post('/hosts/batch_add', batchHostsFormData).then((res) => {
          if (res.status === 201) {
            ElMessage.success(res.data);
            getData();
            isLoading.value = false
            showBatchAddHost.value = false;
          }
        }).catch((err) => {
          ElMessage.error(err.data);
        });
      } else {
        ElMessage.error('请填写完整的主机信息');
        return;
      }
    });
  }
};
// 批量删除主机
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的主机');
    return;
  }
  ElMessageBox.confirm('确定删除主机吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    isLoading.value = true
    server.post(`/hosts/batch_delete`, {"host_lists": selectedRows.value}).then((res) => {
      if (res.status === 200) {
        ElMessage.success(res.data);
        isLoading.value = false
        getData();
      }
    }).catch((err) => {
      ElMessage.error(err.data);
    })
  })
}
// 批量开关机功能
const handleBatchPowerOn = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要操作的主机！")
    return
  }
  ElMessageBox.confirm('确定执行该操作吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 显示加载提示
    const loadingInstance = ElLoading.service({
      lock: true,
      text: `正在执行，请稍候...`,
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    server.post(`/hosts/power_on`, {"host_lists": selectedRows.value}).then((res) => {
      if (res.status === 200) {
        ElMessage.success(res.data);
        loadingInstance.close()
        getData();
      }
    }).catch((err) => {
      ElMessage.error(err.data);
    })
  })
}
// 批量关机功能
const handleBatchPowerOff = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要操作的主机！")
    return
  }
  ElMessageBox.confirm('确定执行该操作吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 显示加载提示
    const loadingInstance = ElLoading.service({
      lock: true,
      text: `正在执行，请稍候...`,
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    server.post(`/hosts/power_off`, {"host_lists": selectedRows.value}).then((res) => {
      if (res.status === 200) {
        ElMessage.success(res.data);
        loadingInstance.close()
        getData();
      }
    }).catch((err) => {
      ElMessage.error(err.data);
    })
  })
}
</script>

<template>
  <div class="bg-cover">
    <el-container>
      <el-header>
        <div class="f-header">
          <h1 class="text-xl font-bold mt-5 mb-2">资金卡批量升级</h1>
        </div>
      </el-header>
      <el-main>
        <div class="mb-2">
          <el-button type="primary" @click="showFormDrawerDiag">添加主机</el-button>
          <el-button type="primary" @click="handleBatchAddHost">批量添加主机</el-button>
          <el-button type="success" @click="openFirmwareDiag">固件管理</el-button>
          <el-button type="danger" @click="handleBatchDelete" :loading="isLoading">删除主机</el-button>

          <!-- 点击按钮调用开始升级任务的方法 -->
          <el-button type="success" @click="startUpgradeSelectFirmware" :disabled="isUpgrading">
            {{ isUpgrading ? '升级中...' : '开始升级' }}
          </el-button>
          <el-button type="success" @click="handleBatchPowerOn">开机</el-button>
          <el-button type="danger" @click="handleBatchPowerOff">强制关机</el-button>
          <!-- 显示进度条 -->
          <el-progress
              v-if="isUpgrading"
              :percentage="upgradeProgress"
              :status="upgradeProgress === 100 ? 'success' : 'active'"
              :stroke-width="15"
              striped
              striped-flow
          />

        </div>
        <div class="flex justify-between">
          <el-table ref="hostInfoTableRef" :data="tableData" stripe :height="tableHeight + 'px'"
                    @selection-change="handleSelectionChange">
            <!-- 添加多选列 -->
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="id" label="编号" width="80"/>
            <el-table-column prop="host_ip" label="主机IP地址" width="150" sortable/>
            <el-table-column prop="username" label="用户名" width="150"/>
            <el-table-column prop="upgrade_status" label="升级状态" width="120" sortable>
              <template #default="scope">
                <el-tag v-if="scope.row.upgrade_status === 'IN_PROGRESS'" type="info">升级中</el-tag>
                <el-tag v-if="scope.row.upgrade_status === 'COMPLETED'" type="success">已完成</el-tag>
                <el-tag v-if="scope.row.upgrade_status === 'FAILED'" type="danger">升级失败</el-tag>
                <el-tag v-if="scope.row.upgrade_status === 'NOTSTARTED'">未开始</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="upgrade_log" label="升级日志" min-width="200"/>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                  编辑
                </el-button>
                <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete( scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty description="NO Data"/>
            </template>
          </el-table>
        </div>
      </el-main>
    </el-container>
  </div>
  <FormDrawer :confirm-text="confirmText" :title="formTitle" ref="addHostDrawerRef" @submit="handleAddHost"
              @drawer-close="onDrawerClose">
    <el-form :label-position="'left'" :label-width="'100px'" ref="formRef" :model="form">
      <el-form-item label="主机IP地址" prop="host_ip">
        <el-input v-model="form.host_ip" placeholder="请输入主机IP地址" :disabled="isUpdating"/>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" placeholder="请输入密码"/>
      </el-form-item>
    </el-form>
  </FormDrawer>
  <!--  固件对话框-->
  <el-dialog v-model="dialogTableVisible" title="固件管理" width="920px">
    <el-form class="flex">
      <el-form-item label="固件类型">
        <el-select v-model="fileType" placeholder="请选择类型" style="width: 200px">
          <!-- 这里根据实际情况添加选项 -->
          <el-option label="BIOS" value="BIOS"></el-option>
          <el-option label="CPLD" value="CPLD"></el-option>
          <el-option label="BMC" value="BMC"></el-option>
          <el-option lable="FPGA" value="FPGA"></el-option>
        </el-select>
      </el-form-item>
      <el-upload
          class="ml-3"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          :file-list="fileList"
          :http-request="customUpload"
          multiple
      >
        <el-button type="primary" :disabled="fileType===''||fileType===null">点击上传</el-button>
      </el-upload>
    </el-form>

    <el-table :data="firmwareList" stripe>
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="id" label="编号" width="70"/>
      <el-table-column property="file_name" label="固件名称" width="400"/>
      <el-table-column property="upload_time" label="上传日期" width="200"/>
      <el-table-column property="type" label="固件类型"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="danger" size="small" @click="handleDeleteFirmware(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
  <!--选择固件对话框-->
  <el-dialog v-model="selectFirmwareDialogVisible" @close="resetSelectFirmwareForm" title="选择固件开始升级"
             style="width: 600px;">
    <el-form :model="uploadedFirmwareList" :label-position="'left'" :label-width="'110px'" ref="selectFirmwareForm">
      <el-form-item label="BIOS固件类型" size="large" v-model="uploadedFirmwareList.biosFirmwareID">
        <el-select v-model="uploadedFirmwareList.biosFirmwareID" placeholder="请选择BIOS升级文件" style="width: 500px"
                   clearable>
          <!-- 这里根据实际情况添加选项 -->
          <el-option
              v-for="item in biosFirmwareList"
              :key="item.id"
              :label="item.file_name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="CPLD固件类型" size="large" v-model="uploadedFirmwareList.cpldFirmwareID">
        <el-select v-model="uploadedFirmwareList.cpldFirmwareID" placeholder="请选择CPLD升级文件" style="width: 500px"
                   clearable>
          <!-- 这里根据实际情况添加选项 -->
          <el-option
              v-for="item in cpldFirmwareList"
              :key="item.id"
              :label="item.file_name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="BMC固件类型" size="large" v-model="uploadedFirmwareList.bmcFirmwareID">
        <el-select v-model="uploadedFirmwareList.bmcFirmwareID" placeholder="请选择BMC升级文件" style="width: 500px"
                   clearable>
          <!-- 这里根据实际情况添加选项 -->
          <el-option
              v-for="item in bmcFirmwareList"
              :key="item.id"
              :label="item.file_name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="FPGA固件类型" size="large" v-model="uploadedFirmwareList.fpgaFirmwareID">
        <el-select v-model="uploadedFirmwareList.fpgaFirmwareID" placeholder="请选择FPGA升级文件" style="width: 500px"
                   clearable>
          <!-- 这里根据实际情况添加选项 -->
          <el-option
              v-for="item in fpgaFirmwareList"
              :key="item.id"
              :label="item.file_name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否强制关机" size="large" v-model="uploadedFirmwareList.isForceRestart" clearable>
        <el-select v-model="uploadedFirmwareList.isForceRestart" style="width: 500px"
                   placeholder="请选择是否强制关机升级!" clearable>
          <el-option
              v-for="(item,index) in forceRestartOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="startUpgradeTaskConfirm">开始升级</el-button>
      </el-form-item>
    </el-form>

  </el-dialog>

  <!--批量添加主机-->
  <el-dialog v-model="showBatchAddHost" title="批量添加主机" width="400px">
    <!-- 通过 :rules 属性绑定校验规则 -->
    <el-form label-width="100" :model="batchHostsFormData" ref="batchHostsFormRef" :rules="batchHostsFormRules">
      <!-- 通过 prop 属性指定对应字段 -->
      <el-form-item label="起始IP地址" prop="start_ip">
        <el-input placeholder="请输入起始IP地址" clearable class="batch-input" v-model="batchHostsFormData.start_ip"/>
      </el-form-item>
      <el-form-item label="结束IP地址" prop="end_ip">
        <el-input placeholder="请输入结束IP地址" clearable class="batch-input" v-model="batchHostsFormData.end_ip"/>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input placeholder="请输入Redfish用户名" clearable class="batch-input"
                  v-model="batchHostsFormData.username"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" placeholder="请输入Redfish密码" clearable class="batch-input"
                  v-model="batchHostsFormData.password"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleBatchAddHostSubmit" :loading="isLoading">确认提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped>
.f-header {
  @apply flex justify-center bg-indigo-700 text-light-50 fixed top-0 left-0 right-0 items-center;
  height: 64px;
}

.batch-input {
  width: 200px;
}
</style>